import React from 'react';
import { Card, Row, Col, Tag, Typography, Space, Progress, Descriptions } from 'antd';
import {
  ClockCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  DatabaseOutlined,
  CodeOutlined,
  SettingOutlined,
  SafetyCertificateOutlined,
  GitlabOutlined,
  GithubOutlined,
  InfoCircleOutlined,
  ThunderboltOutlined,
  RobotOutlined,
  PlayCircleOutlined,
  SyncOutlined
} from '@ant-design/icons';
import { EnhancedScanTaskResponse } from '../../types/taskDetail';
import './TaskExecutionInfo.css';

const { Text, Title } = Typography;

interface TaskProgressInfo {
  isConnected: boolean;
  currentProgress: number;
  currentStage: string;
  currentMessage: string;
  isMilestone: boolean;
  milestoneTitle?: string;
  milestoneDescription?: string;
  estimatedRemainingSeconds?: number;
}

interface TaskExecutionInfoProps {
  task: EnhancedScanTaskResponse;
  progressInfo?: TaskProgressInfo;
}

const TaskExecutionInfo: React.FC<TaskExecutionInfoProps> = ({ task, progressInfo }) => {
  
  // 获取阶段显示名称
  const getStageDisplayName = (stage: string) => {
    const stageMap: { [key: string]: string } = {
      'INITIALIZATION': '初始化',
      'CONFIG_VALIDATION': '配置验证',
      'GIT_CLONE_START': '开始下载代码',
      'GIT_CLONING': '正在下载代码',
      'GIT_CLONE_COMPLETE': '代码下载完成',
      'CODE_SCANNING': '扫描源码文件',
      'SQL_EXTRACTION_START': '开始SQL提取',
      'SQL_PARSING': '解析SQL语句',
      'SQL_EXTRACTION_COMPLETE': 'SQL提取完成',
      'SQL_SAVING': '保存SQL语句',
      'RULE_ANALYSIS_START': '开始规则分析',
      'RULE_LOADING': '加载兼容性规则',
      'RULE_MATCHING': '匹配规则模式',
      'RULE_RESULT_PROCESSING': '处理规则结果',
      'RULE_ANALYSIS_COMPLETE': '规则分析完成',
      'AI_PREPARATION': 'AI验证准备',
      'AI_DATA_SAVING': '保存规则结果',
      'AI_VERIFICATION_START': '开始AI验证',
      'AI_BATCH_PROCESSING': 'AI批量验证',
      'AI_VERIFICATION_COMPLETE': 'AI验证完成',
      'RESULT_AGGREGATION': '聚合分析结果',
      'RESULT_SAVING': '保存最终结果',
      'STATISTICS_UPDATE': '更新统计信息',
      'CLEANUP': '清理临时文件',
      'COMPLETION': '任务完成'
    };
    return stageMap[stage] || stage;
  };

  // 格式化剩余时间
  const formatRemainingTime = (seconds?: number) => {
    if (!seconds || seconds <= 0) return null;
    if (seconds < 60) return `${seconds}秒`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)}分${seconds % 60}秒`;
    return `${Math.floor(seconds / 3600)}小时${Math.floor((seconds % 3600) / 60)}分钟`;
  };
  
  // 获取任务状态配置
  const getStatusConfig = (status: string) => {
    const configs = {
      PENDING: { color: 'default', text: '待执行', icon: <ClockCircleOutlined />, bgColor: '#faad14' },
      RUNNING: { color: 'processing', text: '执行中', icon: <ClockCircleOutlined />, bgColor: '#1890ff' },
      COMPLETED: { color: 'success', text: '已完成', icon: <CheckCircleOutlined />, bgColor: '#52c41a' },
      SUCCESS: { color: 'success', text: '已完成', icon: <CheckCircleOutlined />, bgColor: '#52c41a' },
      FAILED: { color: 'error', text: '失败', icon: <ExclamationCircleOutlined />, bgColor: '#ff4d4f' },
      CANCELLED: { color: 'warning', text: '已取消', icon: <ExclamationCircleOutlined />, bgColor: '#faad14' }
    } as const;
    return configs[status as keyof typeof configs] || { color: 'default', text: status, icon: <InfoCircleOutlined />, bgColor: '#d9d9d9' };
  };

  // 获取任务类型配置
  const getTaskTypeConfig = (taskType: string) => {
    const configs = {
      PROJECT_SCAN: { icon: <CodeOutlined />, color: '#1890ff', text: '项目扫描' },
      GIT_SCAN: { icon: <GitlabOutlined />, color: '#52c41a', text: 'Git扫描' },
      GIT_SOURCE_SCAN: { icon: <GitlabOutlined />, color: '#52c41a', text: 'Git源码扫描' },
      DATABASE_SCAN: { icon: <DatabaseOutlined />, color: '#fa8c16', text: '数据库扫描' },
      DATABASE_DDL_SCAN: { icon: <DatabaseOutlined />, color: '#fa8c16', text: '数据库DDL扫描' },
      MIXED_SCAN: { icon: <SettingOutlined />, color: '#722ed1', text: '混合扫描' },
      MANUAL_SQL: { icon: <CodeOutlined />, color: '#13c2c2', text: '手动SQL' }
    } as const;
    return configs[taskType as keyof typeof configs] || { icon: <InfoCircleOutlined />, color: '#1890ff', text: taskType };
  };

  // 获取分析引擎配置 - 优先使用后端增强字段
  const getAnalysisEngineConfig = (task: EnhancedScanTaskResponse) => {
    // 优先使用后端提供的增强显示字段
    if (task.analysisEngineDisplay) {
      const isAI = task.analysisEngineDisplay.includes('AI');
      return {
        icon: isAI ? <RobotOutlined /> : <ThunderboltOutlined />,
        color: isAI ? 'purple' : 'blue',
        text: task.analysisEngineDisplay
      };
    }
    
    // 后备方案：从配置中解析
    const config = task.config || {};
    const engine = config.analysisEngine;
    
    const configs = {
      RULE_BASED: { icon: <ThunderboltOutlined />, color: 'blue', text: '规则引擎' },
      LLM_BASED: { icon: <RobotOutlined />, color: 'purple', text: 'AI引擎' },
      AI_ANALYSIS: { icon: <RobotOutlined />, color: 'purple', text: 'AI引擎' },
      AI: { icon: <RobotOutlined />, color: 'purple', text: 'AI引擎' }
    } as const;
    
    return configs[engine as keyof typeof configs] || { icon: <ThunderboltOutlined />, color: 'blue', text: '规则引擎' };
  };

  // 获取Git平台图标
  const getGitPlatformIcon = (platform?: string) => {
    switch (platform?.toLowerCase()) {
      case 'gitlab':
        return <GitlabOutlined style={{ color: '#fc6d26' }} />;
      case 'github':
        return <GithubOutlined style={{ color: '#333' }} />;
      case 'gitee':
        return <CodeOutlined style={{ color: '#c71d23' }} />;
      default:
        return <GitlabOutlined style={{ color: '#fc6d26' }} />;
    }
  };

  // 格式化时间
  const formatDuration = (start?: string, end?: string) => {
    if (!start) return '未开始';
    if (!end && task.status === 'RUNNING') {
      const duration = Date.now() - new Date(start).getTime();
      const minutes = Math.floor(duration / (1000 * 60));
      const seconds = Math.floor((duration % (1000 * 60)) / 1000);
      return `${minutes}分${seconds}秒`;
    }
    if (end) {
      const duration = new Date(end).getTime() - new Date(start).getTime();
      const minutes = Math.floor(duration / (1000 * 60));
      const seconds = Math.floor((duration % (1000 * 60)) / 1000);
      return `${minutes}分${seconds}秒`;
    }
    return '计算中...';
  };

  const statusConfig = getStatusConfig(task.status);
  const typeConfig = getTaskTypeConfig(task.taskType);
  const config = task.config || {};

  return (
    <div className="task-execution-info">
      <Row gutter={[16, 16]}>
        {/* 执行状态卡片 */}
        <Col xs={24} lg={8}>
          <Card 
            className="execution-status-card"
            bodyStyle={{ padding: 20, textAlign: 'center' }}
          >
            <div className="status-header">
              <Title level={4} style={{ color: statusConfig.bgColor, marginBottom: 16 }}>
                {statusConfig.text}
                {progressInfo && progressInfo.isConnected && task.status === 'RUNNING' && (
                  <SyncOutlined spin style={{ marginLeft: 8, fontSize: 16, color: '#1890ff' }} />
                )}
              </Title>
            </div>
            
            {/* 实时进度信息 */}
            {task.status === 'RUNNING' && (
              <div className="progress-section" style={{ marginBottom: 16 }}>
                {/* WebSocket连接状态 */}
                {progressInfo && (
                  <div style={{ marginBottom: 12 }}>
                    <Space>
                      {progressInfo.isConnected ? (
                        <Tag color="success">实时更新</Tag>
                      ) : (
                        <Tag color="warning">连接中...</Tag>
                      )}
                    </Space>
                  </div>
                )}

                {/* 当前阶段 */}
                {progressInfo && progressInfo.currentStage && (
                  <div style={{ marginBottom: 8 }}>
                    <Space>
                      <Text strong style={{ fontSize: 12 }}>当前阶段:</Text>
                      <Tag color="blue">
                        {getStageDisplayName(progressInfo.currentStage)}
                      </Tag>
                      {progressInfo.isMilestone && (
                        <Tag color="gold" icon={<PlayCircleOutlined />}>
                          里程碑
                        </Tag>
                      )}
                    </Space>
                  </div>
                )}

                {/* 进度条 */}
                <div style={{ marginBottom: 8 }}>
                  <Text type="secondary" style={{ fontSize: 12, marginBottom: 8, display: 'block' }}>
                    执行进度: {progressInfo?.currentProgress || task.progress || 0}%
                  </Text>
                  <Progress 
                    percent={progressInfo?.currentProgress || task.progress || 0} 
                    status={progressInfo?.currentProgress === 100 ? 'success' : 'active'} 
                    strokeColor={progressInfo?.isMilestone ? '#52c41a' : {
                      '0%': '#108ee9',
                      '100%': '#87d068',
                    }}
                    size="small"
                    showInfo={false}
                  />
                </div>

                {/* 当前状态消息 */}
                {progressInfo && progressInfo.currentMessage && (
                  <Text type="secondary" style={{ fontSize: 11, display: 'block', marginBottom: 8 }}>
                    {progressInfo.currentMessage}
                  </Text>
                )}

                {/* 预估剩余时间 */}
                {progressInfo && formatRemainingTime(progressInfo.estimatedRemainingSeconds) && (
                  <Text type="secondary" style={{ fontSize: 11, display: 'block' }}>
                    预估剩余: {formatRemainingTime(progressInfo.estimatedRemainingSeconds)}
                  </Text>
                )}

                {/* 里程碑信息 */}
                {progressInfo && progressInfo.isMilestone && progressInfo.milestoneTitle && (
                  <Card 
                    size="small" 
                    style={{ 
                      background: '#f6ffed', 
                      border: '1px solid #b7eb8f',
                      marginTop: 12,
                      textAlign: 'left'
                    }}
                    bodyStyle={{ padding: 8 }}
                  >
                    <Space direction="vertical" size={4}>
                      <Text strong style={{ color: '#389e0d', fontSize: 12 }}>
                        🎯 {progressInfo.milestoneTitle}
                      </Text>
                      {progressInfo.milestoneDescription && (
                        <Text style={{ fontSize: 11 }}>{progressInfo.milestoneDescription}</Text>
                      )}
                    </Space>
                  </Card>
                )}
              </div>
            )}
            
            <div className="time-info">
              <Row gutter={[8, 8]} style={{ width: '100%' }}>
                <Col span={12} style={{ textAlign: 'center' }}>
                  <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 4 }}>执行用时</Text>
                  <Text strong style={{ fontSize: 14 }}>{formatDuration(task.startTime, task.endTime)}</Text>
                </Col>
                {task.startTime && (
                  <Col span={12} style={{ textAlign: 'center' }}>
                    <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 4 }}>开始时间</Text>
                    <Text style={{ fontSize: 12, wordBreak: 'keep-all', whiteSpace: 'nowrap' }}>
                      {new Date(task.startTime).toLocaleString()}
                    </Text>
                  </Col>
                )}
              </Row>
            </div>
          </Card>
        </Col>

        {/* 基础配置信息 */}
        <Col xs={24} lg={10}>
          <Card 
            title={
              <Space>
                <SettingOutlined />
                <span>任务配置</span>
              </Space>
            }
            className="task-config-card"
            bodyStyle={{ padding: 20 }}
          >
            <Descriptions column={1} size="small" layout="horizontal" colon={true} labelStyle={{ width: '90px', textAlign: 'left', fontWeight: 500, fontSize: '12px' }}>
              <Descriptions.Item label="任务类型">
                <Space>
                  {typeConfig.icon}
                  <Tag color={typeConfig.color}>{typeConfig.text}</Tag>
                </Space>
              </Descriptions.Item>

              <Descriptions.Item label="兼容性检查">
                <Space>
                  <Tag color="blue" icon={<DatabaseOutlined />}>
                    {task.sourceDbType || config.sourceDbType || 'MYSQL'}
                  </Tag>
                  <span>→</span>
                  <Tag color="green" icon={<SafetyCertificateOutlined />}>
                    {task.targetDbType || config.targetDbType || 'GOLDENDB'}
                  </Tag>
                </Space>
              </Descriptions.Item>

              <Descriptions.Item label="分析引擎">
                <Space>
                  {(() => {
                    const engineConfig = getAnalysisEngineConfig(task);
                    return (
                      <Tag color={engineConfig.color} icon={engineConfig.icon}>
                        {engineConfig.text}
                      </Tag>
                    );
                  })()}
                  {/* AI增强状态 */}
                  {(task.aiEnhancementEnabled || config.aiEnhancementEnabled) && (
                    <Tag color="purple" icon={<RobotOutlined />}>
                      AI增强
                    </Tag>
                  )}
                </Space>
              </Descriptions.Item>

              {task.projectName && (
                <Descriptions.Item label="关联项目">
                  <Tag color="purple" icon={<CodeOutlined />}>
                    {task.projectName}
                  </Tag>
                </Descriptions.Item>
              )}

              {/* Git仓库信息 - 只在Git相关任务中显示 */}
              {(task.taskType === 'GIT_SCAN' || task.taskType === 'GIT_SOURCE_SCAN' || task.taskType === 'MIXED_SCAN') && (
                <>
                  {(config.repositoryUrl || config.gitRepositoryUrl) && (
                    <Descriptions.Item label="Git仓库">
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                        <Space>
                          {getGitPlatformIcon(config.gitPlatform)}
                          <Text 
                            code 
                            style={{ 
                              fontSize: 11, 
                              maxWidth: 280, 
                              overflow: 'hidden', 
                              textOverflow: 'ellipsis', 
                              whiteSpace: 'nowrap',
                              cursor: 'default'
                            }}
                            title={config.repositoryUrl || config.gitRepositoryUrl}
                          >
                            {(() => {
                              const url = config.repositoryUrl || config.gitRepositoryUrl;
                              // 提取仓库名称部分显示
                              const repoName = url?.split('/').pop()?.replace('.git', '') || url;
                              // 如果URL很长，只显示仓库名，否则显示完整URL
                              return url && url.length > 40 ? `.../${repoName}` : url;
                            })()}
                          </Text>
                        </Space>
                        {(task.branchName || config.branchName) && (
                          <Space size={4}>
                            <span style={{ fontSize: 11, color: '#666' }}>分支:</span>
                            <Tag color="geekblue" style={{ fontFamily: 'monospace' }}>
                              {task.branchName || config.branchName}
                            </Tag>
                          </Space>
                        )}
                      </div>
                    </Descriptions.Item>
                  )}
                </>
              )}

              {/* 数据库信息 - 只在数据库相关任务中显示 */}
              {(task.taskType === 'DATABASE_SCAN' || task.taskType === 'DATABASE_DDL_SCAN' || task.taskType === 'MIXED_SCAN') && (
                <>
                  {config.databaseHost && (
                    <Descriptions.Item label="数据库连接">
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                        <Space>
                          <DatabaseOutlined style={{ color: '#fa8c16' }} />
                          <Text code style={{ fontSize: 11 }}>
                            {config.databaseHost}:{config.databasePort || 1521}
                          </Text>
                        </Space>
                        {config.databaseName && (
                          <Space size={4}>
                            <span style={{ fontSize: 11, color: '#666' }}>数据库:</span>
                            <Tag color="orange">{config.databaseName}</Tag>
                          </Space>
                        )}
                        {config.databaseType && (
                          <Space size={4}>
                            <span style={{ fontSize: 11, color: '#666' }}>类型:</span>
                            <Tag color="blue">{config.databaseType}</Tag>
                          </Space>
                        )}
                      </div>
                    </Descriptions.Item>
                  )}
                </>
              )}

              {/* 扫描配置信息 */}
              {config.includeDirectories && config.includeDirectories.length > 0 && (
                <Descriptions.Item label="扫描目录">
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 2 }}>
                    {config.includeDirectories.slice(0, 2).map((dir: string, index: number) => (
                      <Tag key={index} color="cyan" style={{ fontSize: 10, margin: 0 }}>
                        {dir}
                      </Tag>
                    ))}
                    {config.includeDirectories.length > 2 && (
                      <Tag color="default" style={{ fontSize: 10, margin: 0 }}>
                        +{config.includeDirectories.length - 2}
                      </Tag>
                    )}
                  </div>
                </Descriptions.Item>
              )}

              {config.fileTypes && config.fileTypes.length > 0 && (
                <Descriptions.Item label="文件类型">
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 2 }}>
                    {config.fileTypes.slice(0, 3).map((type: string, index: number) => (
                      <Tag key={index} color="purple" style={{ fontSize: 10, margin: 0 }}>
                        {type}
                      </Tag>
                    ))}
                    {config.fileTypes.length > 3 && (
                      <Tag color="default" style={{ fontSize: 10, margin: 0 }}>
                        +{config.fileTypes.length - 3}
                      </Tag>
                    )}
                  </div>
                </Descriptions.Item>
              )}
            </Descriptions>
          </Card>
        </Col>

        {/* 创建信息 */}
        <Col xs={24} lg={6}>
          <Card 
            title={
              <Space>
                <InfoCircleOutlined />
                <span>任务信息</span>
              </Space>
            }
            className="task-info-card"
            bodyStyle={{ padding: 20 }}
          >
            <Descriptions column={1} size="small" layout="horizontal" colon={true} labelStyle={{ width: '90px', textAlign: 'left', fontWeight: 500, fontSize: '12px' }}>
              <Descriptions.Item label="任务ID">
                <Tag color="blue">#{task.id}</Tag>
              </Descriptions.Item>
              
              <Descriptions.Item label="创建时间">
                <Text style={{ fontSize: 12, display: 'block' }}>
                  {new Date(task.createdAt).toLocaleString()}
                </Text>
              </Descriptions.Item>

              {task.username && (
                <Descriptions.Item label="创建用户">
                  <Tag color="cyan">{task.username}</Tag>
                </Descriptions.Item>
              )}

              {task.errorMessage && (
                <Descriptions.Item label="错误信息">
                  <Text type="danger" style={{ fontSize: 12, wordBreak: 'break-word' }}>
                    {task.errorMessage}
                  </Text>
                </Descriptions.Item>
              )}

              {task.status === 'FAILED' && task.retryCount !== undefined && (
                <Descriptions.Item label="重试次数">
                  <Text>
                    {task.retryCount} / {task.maxRetryCount || 3}
                  </Text>
                </Descriptions.Item>
              )}
            </Descriptions>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default TaskExecutionInfo;